package server;

import util.Logger;
import dataContracts.Command;
import dataContracts.SharedDirectory;
import dataContracts.SharedFile;

class NewFileHandler implements Runnable {
	ClientConnection client;
	ServerProgram server;
	Command command;
	
	NewFileHandler(ClientConnection client, ServerProgram server, Command command) {
		this.server = server;
		this.client = client;
		this.command = command;
	}
	
	@Override
	public void run() {
		// look up file object sent by client
		SharedDirectory dir = command.directoryInfo;
		if (dir != null) {
			Logger.Debug("Trying to find file in provided directory: "+ command.commandBody);
			SharedFile match = dir.findFile(command.commandBody);
			if (match != null) {
				SharedFile serverCopy = server.directory.findFile(command.commandBody);
				// if it doesn't exist, add it
				if (serverCopy == null) {
					serverCopy = server.directory.addFile(command.commandBody);
				} else {
					Logger.Warning("File already exists, attempting metadata update :"+ command.commandBody);
				}
				server.directory.copyMetaData(serverCopy, match);
			} else {
				Logger.Warning("File not found in provided client directory! :"+ command.commandBody);
			}
		}
		
		// update the downloadserver to not call files.add() or at least make that safe.
	}
}